<?php


namespace services\buss;


use common\models\buss\Accounts;
use common\models\buss\AccountsFans;
use services\log\LogMemberOpService;
use Yii;
use common\components\Service;

class AccountsFansService extends Service
{
    /**
     * 粉丝更新记录
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getList(array $params, int $page, int $pageSize): array
    {
        $query = AccountsFans::find()->where(['account_id' => $params['id']]);
        $orderBy['id'] = SORT_DESC;
        return $this->getListPageRes($query, $page, $pageSize, $orderBy);
    }

    /**
     * 更新账号粉丝数
     */
    public function updateAccountsFans(array $params): array
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            // 新增粉丝更新记录
            $fans = new AccountsFans();
            $oldFans = AccountsFans::find()
                ->where(['account_id' => $params['id']])
                ->orderBy(['created_at' => SORT_DESC])
                ->limit(1)
                ->asArray()
                ->one();
            $oldFansNum = $oldFans ? $oldFans['fans_num'] : $params['fans_num'];
            $fans->account_id = $params['id'];
            $fans->fans_num = $params['fans_num'];
            $fans->rate = $params['fans_num'] - $oldFansNum;
            $fans->operation_id = Yii::$app->user->identity->member_id;
            $fans->operation_name = Yii::$app->user->identity->member->realname;
            $fans->update_date = date('Y-m-d H:i:s');
            $fans->saveAndCheckResult();

            // 更新账号fans_id
            $account = Accounts::findOne($params['id']);
            $account->fans_id = $fans->id;
            $account->saveAndCheckResult();

            // 添加日志
            LogMemberOpService::createAccountLog('update_fans', $account, null, $fans);
            $transaction->commit();
            return ['id' => $fans->id];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }
}
